package com.ky.pro.java.nio.http.server.outbound.client.impl.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.CharsetUtil;

/**
 * @ClassName NettyHttpClientHandler
 * @Description TODO
 * @Date 2021/11/20 23:00
 * @Author kevin
 **/
@ChannelHandler.Sharable
public class NettyHttpClientHandler extends ChannelInboundHandlerAdapter {

    public NettyHttpClientHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(ctx.channel().attr(NettyHttpClientImpl.ATTR_KEY_REQUEST).get());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpResponse response = (FullHttpResponse) msg;
        ByteBuf content = response.content();
        HttpHeaders headers = response.headers();
        System.out.println("content:" + content.toString(CharsetUtil.UTF_8));
        System.out.println("headers:" + headers.get("content-type"));
        FullHttpRequest request = ctx.channel().attr(NettyHttpClientImpl.ATTR_KEY_REQUEST).get();
        synchronized (request) {
            ctx.channel().attr(NettyHttpClientImpl.ATTR_KEY_RESPONSE).set(response);
            request.notifyAll();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
